<?php

namespace App\Services\UserUpgrade;

use Carbon\Carbon;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class UserUpgrade
{
	protected ?User $user = null;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

	protected function execute(User $user)
	{

        DB::transaction(function () use ($user) {

             $userReason = "";
             $TeamReason = "";
             $data = [];
            
            $needGradeNumber = cs("sale")->auto_upgrade_needs_children;
            $needTeamNumber = cs("sale")->auto_upteam_needs_children;

          

            if($user->grade == "vip"){
                $userOrderNumber = $user->myOrderChildren()->count();
                if($needGradeNumber <= $userOrderNumber){
                    $userReason = "升级为团长";
                    $data['grade'] = 'commander';
                }   

            }

             if($userReason){
                 $user->upgradeLogs()->create(['reason' => $userReason]);
                

             }


             if($data){

                 $user->update($data);
             }

             if($user->parent && $userReason){

                 user_upgrade($user->parent);
             }

          
        });

	}

	public function upgrade(User $user)
	{
		
		$this->execute($user);
	}
}
